﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace AwesomeChromeFormUI.Configs
{
    public class IniFileParser
    {
        private string _filePath;
        private Dictionary<string, Dictionary<string, string>> _sections;

        public IniFileParser(string filePath)
        {
            _filePath = filePath;
            _sections = new Dictionary<string, Dictionary<string, string>>();
            ParseIniFile();
        }

        private void ParseIniFile()
        {
            if (!File.Exists(_filePath))
            {
                throw new FileNotFoundException("配置文件不存在");
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(_filePath);

            XmlNodeList sectionsNodes = doc.SelectNodes("/INI/Section");
            foreach (XmlNode sectionNode in sectionsNodes)
            {
                string sectionName = sectionNode.Attributes["name"].Value;
                _sections[sectionName] = new Dictionary<string, string>();

                XmlNodeList keyValuePairsNodes = sectionNode.SelectNodes("KeyValuePair");
                foreach (XmlNode keyValuePairNode in keyValuePairsNodes)
                {
                    string key = keyValuePairNode.Attributes["key"].Value;
                    string value = keyValuePairNode.Attributes["value"].Value;
                    _sections[sectionName][key] = value;
                }
            }
        }

        public string GetValue(string sectionName, string key)
        {
            if (!_sections.ContainsKey(sectionName))
            {
                throw new Exception($"未找到名为 {sectionName} 的部分");
            }

            if (!_sections[sectionName].ContainsKey(key))
            {
                throw new KeyNotFoundException($"在 {sectionName} 部分中未找到键 {key}");
            }

            return _sections[sectionName][key];

        }

    }


    public class ForTest
    {
//        [Section1]
//        key1 = value1
//        key2 = value2

//        [Section2]
//key3 = value3
//key4 = value4

        public void Test()
        {
            IniFileParser parser = new IniFileParser("config.ini");
            parser.GetValue("Section1", "key1");
            parser.GetValue("Section1", "key2");
        }
    }
}